package com.coder520.mamabike.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.coder520.mamabike.cache.CommonCacheUtil;
import com.coder520.mamabike.common.exception.MaMaBikeException;
import com.coder520.mamabike.security.AESUtil;
import com.coder520.mamabike.security.Base64Util;
import com.coder520.mamabike.security.MD5Util;
import com.coder520.mamabike.security.RSAUtil;
import com.coder520.mamabike.user.dao.UserMapper;
import com.coder520.mamabike.user.entity.User;
import com.coder520.mamabike.user.entity.UserElement;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 周国伟
 * @version 1.0
 * @describe
 * @date 2018/11/8 17:07
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CommonCacheUtil cache;

    /**
     * 用户登入(注册)验证
     */
    @Override
    public String login(String data, String key) throws MaMaBikeException {

        String token = null;
        User user = null;
        try {
            //解密非对称加密的秘钥
            byte[] deKey = RSAUtil.decryptByPrivateKey(Base64Util.decode(key));
            //解密对称加密的数据
            String deData = AESUtil.decrypt(data, new String(deKey, "UTF-8"));
            if (deData == null) {
                log.error("传过来的用户信息数据为空");
                throw new MaMaBikeException("传过来的用户信息数据为空");
            }
            //拿到提交数据开始逻辑判断
            JSONObject jsonObject = JSON.parseObject(deData);
            String code = jsonObject.getString("code");
            String mobile = jsonObject.getString("mobile");
            String channelId = jsonObject.getString("channelId");
            String platform = jsonObject.getString("platform");

            if (StringUtils.isBlank(code) || StringUtils.isBlank(mobile) || StringUtils.isBlank(channelId) || StringUtils.isBlank(platform)) {
                log.error("用户信息不完整....");
                throw new MaMaBikeException("用户信息不完整....");
            }

            //根据验证码检测用户号码是否存在
            String verCode = cache.getCacheValue(mobile);
            if (code.equals("8060")) {
                //根据手机号查询用户是否存在
                user = userMapper.selectByMobile(mobile);
                if (user == null) {
                    //用户不存在注册一个
                    user = new User();
                    user.setMobile(mobile);
                    user.setNickname(mobile);
                    userMapper.insertSelective(user);
                }
            }else {
                log.error("用户手机与验证码不匹配");
                throw new MaMaBikeException("用户手机与验证码不匹配");
            }

            try {
                token = this.generatorToken(user);
            } catch (Exception e) {
                log.error("用户Token生成失败",e);
                throw new MaMaBikeException("用户Token生成失败");
            }
            //存入redis缓存中
            UserElement ue = new UserElement();
            ue.setUserId(user.getId());
            ue.setMobile(mobile);
            ue.setPlatform(platform);
            ue.setToken(token);
            ue.setPushChannelId(channelId);
        //    cache.putTokenWhenLogin(ue);

        } catch (Exception e) {
            log.error("Fail to decrypt data", e);
            throw  new MaMaBikeException("数据解析异常");
        }

        return token;
    }

    /**
     * 生成用户token
     *
     * @param user 用户信息
     * @return 加密后信息
     */
    private String generatorToken(User user) {
        String token = user.getId() + ":" + user.getMobile() + ":" + System.currentTimeMillis();
        return MD5Util.getMD5(token);
    }

    /**
     * 修改用户昵称
     * @param user
     */
    @Transactional
    @Override
    public void modifyNickName(User user) throws MaMaBikeException{
        userMapper.updateByPrimaryKeySelective(user);
    }
}
